const {addMenuServe, getMenuServe, getMenuById, updateMenuServe, deleteMenuServe} = require('../serve/menu.serve')
const {dataToTree} = require('../utils/dataConversion')

class MenuController {
    async addMenu(ctx) {
        try {
            const res = await addMenuServe(ctx);
            ctx.body = {
                msg: '添加菜单成功',
                status: 0
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async getMenus(ctx) {
        try {
            const menus = await getMenuServe();
            const newMenu = dataToTree(JSON.parse(JSON.stringify(menus)), 0);
            ctx.body = {
                msg: '获取菜单成功',
                status: 0,
                data: newMenu
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async updateMenu(ctx) {
        const {id} = ctx.params;
        const res = await getMenuById(id);
        if (!res) {
            return ctx.body = {
                status: 1,
                msg: '未找到id对应数据'
            }
        }
        try {
            const res = await updateMenuServe(ctx, id)
            ctx.body = {
                msg: '修改菜单成功',
                status: 0
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }
    }

    async deleteMenu(ctx) {
        const {id} = ctx.params;
        if (!id) {
            return ctx.body = {
                msg: 'id不能为空'
            }
        }
        const res = await getMenuById(id);
        if (!res) {
            return ctx.body = {
                status: 1,
                msg: '未找到id对应数据'
            }
        }
        try {
            const isSuccessDelete = await deleteMenuServe(id);
            ctx.body = {
                msg: '删除菜单成功',
                status: 0,
                data: isSuccessDelete
            }
        } catch (e) {
            ctx.body = {
                msg: e.message,
                status: 1
            }
        }

    }
}

module.exports = new MenuController();
